package com.zry.study

import android.annotation.SuppressLint
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import com.zry.retorfit.ui.TestActivity
import com.zry.study.bean.UpdateFail
import com.zry.study.bean.UpdateProgressBean
import com.zry.study.bean.UpdateSuccess
import com.zry.study.update.UpdateAppService
import com.zry.study.utils.DialogUtil
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : AppCompatActivity() {
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)
		EventBus.getDefault().register(this)
		initView()
	}
	
	private fun initView() {
		nextBtn.setOnClickListener {
			val intent = Intent(this, TestActivity::class.java)
			startActivity(intent)
		}
		
		updateApp()
//		nextBtn01.setOnClickListener {
//			val intent = Intent(this, PhoneActivity::class.java)
//			startActivity(intent)
//		}
	}
	
	private var dialogUtil: DialogUtil? = null
	private var dialogTitle: TextView? = null
	private var dialogProgress: TextView? = null
	private var dialogProgressBar: ProgressBar? = null
	@SuppressLint("SetTextI18n")
	private fun updateApp() {
		dialogUtil = DialogUtil(this, R.layout.dialog_layout, false, 0, 0, 0)
		dialogTitle = dialogUtil?.view?.findViewById(R.id.dialogTitle)
		dialogProgressBar = dialogUtil?.view?.findViewById(R.id.dialogProgressBar)
		dialogProgress = dialogUtil?.view?.findViewById(R.id.dialogProgress)
		val intent = Intent(this, UpdateAppService::class.java)
		startService(intent)
	}
	
	
	@SuppressLint("SetTextI18n")
	@Subscribe(threadMode = ThreadMode.MAIN)
	fun getWeChatData(updateProgressBean: UpdateProgressBean) {
		dialogProgressBar?.progress = updateProgressBean.progress
		dialogProgress?.text = "下载进度" + updateProgressBean.progress.toString() + "%"
	}
	
	@Subscribe(threadMode = ThreadMode.MAIN)
	fun getWeChatData(updateSuccess: UpdateSuccess) {
		Toast.makeText(this, updateSuccess.updataSuccess, Toast.LENGTH_SHORT).show()
		dialogUtil?.dialogDismiss()
	}
	
	@Subscribe(threadMode = ThreadMode.MAIN)
	fun getWeChatData(updateFail: UpdateFail) {
		dialogUtil?.dialogDismiss()
		Toast.makeText(this, updateFail.updataFailMsg, Toast.LENGTH_SHORT).show()
		System.exit(0)
	}
	
	
	
	
	override fun onDestroy() {
		EventBus.getDefault().unregister(this)
		super.onDestroy()
	}
}
